package com.helloblog.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.helloblog.domain.Article;
import com.helloblog.exception.UserDaoException;

import static com.helloblog.utils.DateSourceUtils.*;
public class ArticleDaoImpl {
	public void addArticle(Article a){	
		try {
			QueryRunner qr = new QueryRunner(getDataSource());
			String sql = "insert into article(title,keyword,author,content,release_datetime,source,is_stick,user_id,blog_id) values(?,?,?,?,?,?,?,?,?)";
			Object params[] = {a.getTitle(),a.getKeyWord(),a.getAuthor(),a.getContent(),a.getRelease_datetime(),
					a.getSource(),a.getIs_stick(),a.getUser_id(),a.getBlog_id()
			};
			qr.update(sql, params);
		} catch (Exception e) {
			throw new UserDaoException(e);
		}
	}
	
	public List<Article> listAllArticle(){
		try {
			QueryRunner qr = new QueryRunner(getDataSource());
			String sql = "select *from article";
			return qr.query(sql, new BeanListHandler<Article>(Article.class));
		} catch (Exception e) {
			throw new UserDaoException(e);
		}
	}
	public Article getArticle(String id){
		try {
			QueryRunner qr = new QueryRunner(getDataSource());
			String sql = "select *from article where id=?";
			Object param = id;
			return qr.query(sql, param,new BeanHandler<Article>(Article.class));
		} catch (Exception e) {
			throw new UserDaoException(e);
		}
	}
	public List getArticlesByUserId(String user_id){
		try {
			QueryRunner qr = new QueryRunner(getDataSource());
			String sql = "select *from article where user_id=?";
			Object param = user_id;
			return qr.query(sql,param,new BeanListHandler<Article>(Article.class));
		} catch (Exception e) {
			throw new UserDaoException(e);
		}
	}
	
	public List getArticlesByBlogId(String blog_id){
		try {
			QueryRunner qr = new QueryRunner(getDataSource());
			String sql = "select *from article where blog_id=?";
			Object param = blog_id;
			return qr.query(sql,param,new BeanListHandler<Article>(Article.class));
		} catch (Exception e) {
			throw new UserDaoException(e);
		}
	}
}
